package org.singledog.dogmail.common.excetption;

import lombok.extern.slf4j.Slf4j;
import org.singledog.dogmail.common.entity.CommonResponse;
import org.singledog.dogmail.common.entity.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 统一异常处理
 *
 * @author ZheMing Liu
 * @since 2022.1.19
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandle {

    /**
     * 执行异常
     */
    @ExceptionHandler
    public ResponseEntity executeExceptionHandle(Exception e) {
        log.error(e.getMessage(), e);
        return ResponseEntity.fail();
    }

    /**
     * 业务异常
     */
    @ExceptionHandler
    public ResponseEntity businessExceptionHandle(BusinessException e) {
        log.error(e.getMessage(), e);
        return ResponseEntity.fail(e);
    }

    /**
     * 方法不允许异常
     */
    @ExceptionHandler
    public ResponseEntity handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e) {
        log.error(e.getMessage(), e);
        return ResponseEntity.fail(CommonResponse.REQUEST_METHOD_ERROR);
    }

    /**
     * 参数校验异常，POST请求body
     */
    @ExceptionHandler
    public ResponseEntity exceptionHandler(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        return ResponseEntity.fail(CommonResponse.REQUEST_PARAM_ERROR.getCode(), e.getMessage());
    }

    /**
     * 参数校验异常，GET请求参数
     */
    @ExceptionHandler(BindException.class)
    public ResponseEntity exceptionHandler(BindException e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        return ResponseEntity.fail(CommonResponse.REQUEST_PARAM_ERROR.getCode(), e.getMessage());
    }
}
